/**
 * 安全的API请求包装器
 * 集成组件生命周期检查和错误处理
 */

import request from '@/utils/request.js'
import lifecycleManager from '@/utils/componentLifecycle.js'
import errorMonitoring from '@/utils/errorMonitoring.js'

class SafeApiWrapper {
  constructor() {
    this.pendingRequests = new Map()
  }

  /**
   * 安全的API请求
   * @param {string} componentId - 组件ID
   * @param {string} url - 请求URL
   * @param {Object} options - 请求选项
   */
  async safeRequest(componentId, url, options = {}) {
    // 检查组件状态
    if (componentId && lifecycleManager.isDestroyed(componentId)) {
      throw new Error('组件已销毁，取消请求')
    }

    const requestId = this.generateRequestId()
    const requestConfig = {
      url,
      componentId,
      requestId,
      ...options
    }

    try {
      // 记录待处理请求
      this.addPendingRequest(componentId, requestId)

      // 执行请求
      const result = await request.safeRequest(componentId, requestConfig)

      // 移除待处理请求
      this.removePendingRequest(componentId, requestId)

      return result
    } catch (error) {
      // 移除待处理请求
      this.removePendingRequest(componentId, requestId)

      // 记录错误
      errorMonitoring.logTextUpdateError('SAFE_API_REQUEST_ERROR', error, {
        url,
        componentId,
        requestId,
        options
      })

      throw error
    }
  }

  /**
   * GET请求
   * @param {string} componentId - 组件ID
   * @param {string} url - 请求URL
   * @param {Object} params - 查询参数
   * @param {Object} options - 其他选项
   */
  get(componentId, url, params = {}, options = {}) {
    return this.safeRequest(componentId, url, {
      method: 'GET',
      data: params,
      ...options
    })
  }

  /**
   * POST请求
   * @param {string} componentId - 组件ID
   * @param {string} url - 请求URL
   * @param {Object} data - 请求数据
   * @param {Object} options - 其他选项
   */
  post(componentId, url, data = {}, options = {}) {
    return this.safeRequest(componentId, url, {
      method: 'POST',
      data,
      ...options
    })
  }

  /**
   * PUT请求
   * @param {string} componentId - 组件ID
   * @param {string} url - 请求URL
   * @param {Object} data - 请求数据
   * @param {Object} options - 其他选项
   */
  put(componentId, url, data = {}, options = {}) {
    return this.safeRequest(componentId, url, {
      method: 'PUT',
      data,
      ...options
    })
  }

  /**
   * DELETE请求
   * @param {string} componentId - 组件ID
   * @param {string} url - 请求URL
   * @param {Object} options - 其他选项
   */
  delete(componentId, url, options = {}) {
    return this.safeRequest(componentId, url, {
      method: 'DELETE',
      ...options
    })
  }

  /**
   * 批量请求
   * @param {string} componentId - 组件ID
   * @param {Array} requests - 请求数组
   */
  async batchRequest(componentId, requests) {
    // 检查组件状态
    if (componentId && lifecycleManager.isDestroyed(componentId)) {
      throw new Error('组件已销毁，取消批量请求')
    }

    const results = []
    const errors = []

    for (let i = 0; i < requests.length; i++) {
      // 在每个请求前检查组件状态
      if (componentId && lifecycleManager.isDestroyed(componentId)) {
        errors.push({
          index: i,
          error: new Error('组件在批量请求过程中被销毁')
        })
        break
      }

      try {
        const result = await this.safeRequest(componentId, requests[i].url, requests[i].options)
        results.push({ index: i, result })
      } catch (error) {
        errors.push({ index: i, error })
        
        // 如果是关键请求失败，可以选择中断
        if (requests[i].critical) {
          break
        }
      }
    }

    return { results, errors }
  }

  /**
   * 并发请求
   * @param {string} componentId - 组件ID
   * @param {Array} requests - 请求数组
   */
  async concurrentRequest(componentId, requests) {
    // 检查组件状态
    if (componentId && lifecycleManager.isDestroyed(componentId)) {
      throw new Error('组件已销毁，取消并发请求')
    }

    const promises = requests.map((req, index) => 
      this.safeRequest(componentId, req.url, req.options)
        .then(result => ({ index, result, success: true }))
        .catch(error => ({ index, error, success: false }))
    )

    const results = await Promise.all(promises)
    
    return {
      successful: results.filter(r => r.success),
      failed: results.filter(r => !r.success)
    }
  }

  /**
   * 添加待处理请求
   * @param {string} componentId - 组件ID
   * @param {string} requestId - 请求ID
   */
  addPendingRequest(componentId, requestId) {
    if (!componentId) return

    if (!this.pendingRequests.has(componentId)) {
      this.pendingRequests.set(componentId, new Set())
    }
    
    this.pendingRequests.get(componentId).add(requestId)

    // 添加到生命周期管理器的清理任务
    lifecycleManager.addCleanupTask(componentId, () => {
      this.cancelComponentRequests(componentId)
    })
  }

  /**
   * 移除待处理请求
   * @param {string} componentId - 组件ID
   * @param {string} requestId - 请求ID
   */
  removePendingRequest(componentId, requestId) {
    if (!componentId) return

    const requests = this.pendingRequests.get(componentId)
    if (requests) {
      requests.delete(requestId)
      
      if (requests.size === 0) {
        this.pendingRequests.delete(componentId)
      }
    }
  }

  /**
   * 取消组件的所有请求
   * @param {string} componentId - 组件ID
   */
  cancelComponentRequests(componentId) {
    const requests = this.pendingRequests.get(componentId)
    if (requests) {
      console.log(`取消组件 ${componentId} 的 ${requests.size} 个待处理请求`)
      requests.clear()
      this.pendingRequests.delete(componentId)
    }
  }

  /**
   * 生成请求ID
   * @returns {string}
   */
  generateRequestId() {
    return `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  }

  /**
   * 获取统计信息
   * @returns {Object}
   */
  getStats() {
    const stats = {
      totalComponents: this.pendingRequests.size,
      totalPendingRequests: 0,
      componentDetails: {}
    }

    this.pendingRequests.forEach((requests, componentId) => {
      stats.totalPendingRequests += requests.size
      stats.componentDetails[componentId] = requests.size
    })

    return stats
  }

  /**
   * 清理过期的待处理请求
   */
  cleanup() {
    const componentsToClean = []
    
    this.pendingRequests.forEach((requests, componentId) => {
      if (lifecycleManager.isDestroyed(componentId)) {
        componentsToClean.push(componentId)
      }
    })

    componentsToClean.forEach(componentId => {
      this.cancelComponentRequests(componentId)
    })
  }
}

// 创建全局实例
const safeApi = new SafeApiWrapper()

// 定期清理
setInterval(() => {
  safeApi.cleanup()
}, 30000) // 每30秒清理一次

// 导出便捷方法
export const safeGet = (componentId, url, params, options) => {
  return safeApi.get(componentId, url, params, options)
}

export const safePost = (componentId, url, data, options) => {
  return safeApi.post(componentId, url, data, options)
}

export const safePut = (componentId, url, data, options) => {
  return safeApi.put(componentId, url, data, options)
}

export const safeDelete = (componentId, url, options) => {
  return safeApi.delete(componentId, url, options)
}

export const safeBatchRequest = (componentId, requests) => {
  return safeApi.batchRequest(componentId, requests)
}

export const safeConcurrentRequest = (componentId, requests) => {
  return safeApi.concurrentRequest(componentId, requests)
}

export default safeApi